﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KmSql.Shared
{
    public static class KmHelper
    {
        public static List<T> ToList<T>(this DataTable dt) where T : class
        {
            var list = new List<T>();
            if (dt == null || dt.Rows.Count == 0)
                return list;
            Type type = typeof(T);
            foreach (DataRow dr in dt.Rows)
            {
                T? t = Activator.CreateInstance(type, true) as T;
                if (t != null)
                {
                    foreach (var propertie in type.GetProperties())
                    {
                        if (dt.Columns.Contains(propertie.Name))
                            propertie.SetValue(t, dr[propertie.Name]);
                    }
                    list.Add(t);
                }
            }
            return list;
        }

        public static T? ToEntity<T>(this DataRow dr) where T : class
        {
            Type type = typeof(T);
            T? t = Activator.CreateInstance(type, true) as T;
            if (t == null)
                return null;
            foreach (var propertie in type.GetProperties())
            {
                if (dr.Table.Columns.Contains(propertie.Name))
                    propertie.SetValue(t, dr[propertie.Name]);
            }
            return t;
        }
    }
}
